let captchaText = ""; // 存储当前验证码

// 生成随机验证码
function generateCaptcha(length = 4) {
    const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let captcha = "";
    for (let i = 0; i < length; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return captcha;
}

// 刷新验证码
function refreshCaptcha() {
    captchaText = generateCaptcha();
    document.getElementById("captchaImg").textContent = captchaText;
    document.getElementById("captchaResult").textContent = "";
}

// 验证验证码
function verifyCaptcha() {
    const userCaptcha = document.getElementById("captchaInput").value.trim();
    const resultDiv = document.getElementById("captchaResult");
    let isValid=true;


    if (userCaptcha === "") {
        showError("验证码不能为空");
        isValid = false;
    } else if (userCaptcha !== captchaText) {
        showError("验证码错误");
        isValid = false;
    } else {
        resultDiv.textContent = "验证码正确";
        resultDiv.style.color = "green";
    }
    // return isValid;
    if (!isValid) refreshCaptcha(); // 验证失败时刷新
    {
        return isValid;
    }
}


// 新增表单全局验证
function validateForm(event) {
    event.preventDefault(); // 阻止默认提交
    const errorDiv = document.getElementById("errorMessage");
    errorDiv.textContent = ""; // 清空旧错误

    // 基础校验
    if (!document.getElementById("username").value.trim()) {
        showError("用户名不能为空");
        return false;
    }
    if (!document.getElementById("password").value.trim()) {
        showError("密码不能为空");
        return false;
    }

    // 验证码校验
    if (!verifyCaptcha()) {
        return false;
    }

    // 所有校验通过后提交表单
    event.target.submit();
}

// 统一错误显示函数
function showError(msg) {
    const errorDiv = document.getElementById("errorMessage");
    errorDiv.textContent = msg;
    errorDiv.style.display = "block";
}
// 页面加载时生成初始验证码
window.onload = function() {
    refreshCaptcha();
};